package com.xhy.documents_collection.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.cache.UserCache;
import com.xhy.documents_collection.entity.PO.team.Team;
import com.xhy.documents_collection.entity.PO.team.TeamUser;
import com.xhy.documents_collection.service.team.TeamService;
import com.xhy.documents_collection.service.team.TeamUserService;
import com.xhy.documents_collection.utils.JwtUtils;
import com.xhy.documents_collection.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author: Xhy
 * CreateTime: 2022-11-21 11:10
 * 用于所属团队
 */

@RestController
@RequestMapping("/user/team")
public class UTeamController {

    @Resource
    private TeamService teamService;

    @Resource
    private TeamUserService teamUserService;


    @GetMapping("/page")
    @Authority("user:team:page")
    public R recordPage(@RequestParam(value = "page") Long current,
                        @RequestParam(value = "limit") Long limit,
                        @RequestParam(required = false) String name,
                        HttpServletRequest request
    ) {
        String uId = JwtUtils.getMemberIdByJwtToken(request);

        // 查出用户所属的团队 -> 团队用户表中查出
        List<Integer> teamId = teamUserService.list(new QueryWrapper<TeamUser>().eq("u_id", uId))
                .stream()
                .map(TeamUser::getTId)
                .collect(Collectors.toList());
        R r = R.ok();
        if (!ObjectUtils.isEmpty(teamId)){
            Page<Team> page = teamService.page(new Page<>(current, limit),
                    new QueryWrapper<Team>().in("id", teamId).like(!ObjectUtils.isEmpty(name), "name", name));
            // 填充信息
            for (Team team : page.getRecords()) {
                team.setCount(teamUserService.count(new QueryWrapper<TeamUser>().eq("t_id",team.getId())));
                team.setUserName(UserCache.get(team.getUId()));
            }

            return r.data("data",page.getRecords()).count(page.getTotal());
        }

        return r;
    }

}
